package jwt.jpa;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.List;


public class Main {

    @SuppressWarnings("unchecked")
    public static void main(final String[] args) {
        BasicConfigurator.configure();
        Logger.getLogger("org").setLevel(Level.ERROR);

        final EntityManagerFactory emf = Persistence
                .createEntityManagerFactory("examplePersistenceUnit");
        final EntityManager em = emf.createEntityManager();

        final Address a1 = new Address("A Rd.", "", "Dallas", "TX", "75001");
        final Person p1 = new Person("Brett", 'L', "Schuchert", a1);

        final Address a2 = new Address("B Rd.", "S2", "OkC", "OK", "73116");
        final Person p2 = new Person("FirstName", 'K', "LastName", a2);

        final Company c1 = new Company();
        c1.setName("The Company");
        c1.setAddress(new Address("D Rd.", "", "Paris", "TX", "77382"));
        c1.hire(p1);
        c1.hire(p2);

        em.getTransaction().begin();
        em.persist(p1);
        em.persist(p2);
        em.persist(c1);
        em.getTransaction().commit();

        final List<Person> list = em.createQuery("select p from Person p")
                .getResultList();

        System.out.printf("People Found\n");
        for (Person current : list) {
            System.out.printf("\t%s works for %s\n", current.getFirstName(),
                    current.getJob().getName());
        }

        Company foundCompany = findCompanyNamed(em, "The Company");

        System.out.printf("Found: %s with %d employees\n",
                foundCompany.getName(), foundCompany.getEmployees().size());

        em.getTransaction().begin();
        c1.fire(p2);
        em.getTransaction().commit();

        foundCompany = findCompanyNamed(em, "The Company");
        System.out.printf("Found: %s with %d employees\n",
                foundCompany.getName(), foundCompany.getEmployees().size());

        for (Person current : foundCompany.getEmployees()) {
            System.out.printf("%s works for %s\n", current.getFirstName(),
                    current.getJob().getName());
        }
    }

    private static Company findCompanyNamed(EntityManager em, String name) {
        return (Company) em.createQuery(
                "select c from Company c where c.name=?1")
                .setParameter(1, name).getSingleResult();

    }
}